package com.makemoney.miniprogram.security.component;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

public class CustomSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    private final Map<RequestMatcher, Collection<ConfigAttribute>> requestMap = new HashMap<>();

    public CustomSecurityMetadataSource() {
        // 初始化请求与权限的映射
        requestMap.put(new AntPathRequestMatcher("/public/**"), Collections.singletonList(new SecurityConfig("permitAll")));
        requestMap.put(new AntPathRequestMatcher("/admin/**"), Collections.singletonList(new SecurityConfig("ROLE_ADMIN")));
        // 其他URL与权限的映射
    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        HttpServletRequest request = ((FilterInvocation) object).getRequest();
        for (Map.Entry<RequestMatcher, Collection<ConfigAttribute>> entry : requestMap.entrySet()) {
            if (entry.getKey().matches(request)) {
                return entry.getValue();
            }
        }
        return null; // 默认返回null表示允许访问
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return requestMap.values().stream().flatMap(Collection::stream).collect(Collectors.toSet());
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
